/*
 * @Author: xiehangyun 
 * @Date: 2025-05-10 18:19:41 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-09-03 20:47:56
 */

import { ArrowRight, Location } from '@nutui/icons-react-taro';
import { Button, Cell, Checkbox, Price } from '@nutui/nutui-react-taro';
import { Image, Text, View } from '@tarojs/components';
import Taro, { useDidShow } from "@tarojs/taro";
import { autorun } from "mobx";
import { ReactNode, useEffect, useRef, useState } from "react";
import utilsApi from 'src/api/utilsApi';
import CustomHeader from 'src/components/CustomHeader/CustomHeader';
import CustomTabBar from 'src/components/CustomTabBar/CustomTabBar';
import shoppingCartStore from 'src/pages/ShoppingCart/shoppingCartStore';
import utils from 'src/utils/utils';
import { CouponItem, DistributionModeData, ReceiveAddress, ShopCarData } from 'types/type';
import addressManageStore from '../AddressManage/addressManageStore';
import myCouponsStore from '../MyCoupons/MyCouponsStore';
import myOrderApi from '../MyOrder/myOrderApi';
import styles from "./confirmOrder.module.less";
import confirmOrderApi from './ConfirmOrderApi';
import confirmOrderStore from './ConfirmOrderStore';
import { observer } from "mobx-react-lite";
import clsx from 'clsx';

interface Iprops {
    children?: ReactNode
}

// 确认订单
const ConfirmOrder = observer((props: Iprops) => {

    const [cartItems, setCartItems] = useState<Array<ShopCarData>>(shoppingCartStore.list);

    const [address, setAddress] = useState<Array<ReceiveAddress>>(addressManageStore.list);
    const [selectedAddressId, setSelectedAddressId] = useState<number>(addressManageStore.selectedAddressId);

    const [distributionMode, setDistributionMode] = useState<Array<DistributionModeData>>(confirmOrderStore.distributionMode);
    const [activeDistributionMode, setActiveDistributionMode] = useState<number>(confirmOrderStore.activeDistributionMode);


    const [packgeType, setPackgeType] = useState<number>(confirmOrderStore.packgeType); // 添加包裹类型状态
    const [commonPackage, setCommonPackage] = useState<number>(confirmOrderStore.commonPackage); // 普通包装
    const [advencedPackage, setAdvencedPackage] = useState<number>(confirmOrderStore.advencedPackage); // 高级包装

    // 在组件内部添加以下状态
    const [packageImages, setPackageImages] = useState<{ common: string, advanced: string }>({ common: '', advanced: '' });

    useEffect(() => autorun(() => {
        setAddress(addressManageStore.list);
        setSelectedAddressId(addressManageStore.selectedAddressId);
        setDistributionMode(confirmOrderStore.distributionMode);
        setActiveDistributionMode(confirmOrderStore.activeDistributionMode);
        setPackgeType(confirmOrderStore.packgeType);
        setCommonPackage(confirmOrderStore.commonPackage);
        setAdvencedPackage(confirmOrderStore.advencedPackage);
        setCoupon(confirmOrderStore.coupon);
    }, { delay: 30 }), []);

    useEffect(() => autorun(() => {
        const { list, selectedItemIds } = shoppingCartStore;
        const selectCartItems = list.filter(item => selectedItemIds.includes(item.id));
        setCartItems(selectCartItems);

        // 计算总价格逻辑
        confirmOrderApi.calculateDeliveryPrice({
            shopCartIds: selectedItemIds.join(','),
            appAddressId: String(addressManageStore.selectedAddressId),
            distributionModeId: String(confirmOrderStore.activeDistributionMode),
            packagePriceType: String(confirmOrderStore.packgeType),
            couponId: confirmOrderStore.coupon ? confirmOrderStore.coupon.couponGetRecordId : 0,
        }).then(res => {
            setTotalPrice(res.data || 0);
        })
    }, { delay: 30 }), []);

    // 添加获取包装图片的 useEffect
    useEffect(() => {
        // 获取包装图片
        const getPackageImages = async () => {
            try {
                const packgeImas = await utilsApi.queryPropertyByTitle("package_image");
                console.log("packgeImas", packgeImas);
                setPackageImages({
                    common: utils.ossSuffix(packgeImas[0].url, 1024),
                    advanced: utils.ossSuffix(packgeImas[1].url, 1024)
                });
            } catch (error) {
                console.error('获取包装图片失败:', error);
            }
        };
        getPackageImages();

        myCouponsStore.setState("未使用");
        addressManageStore.setSelectMode(false);
    }, []);

    const [remark, setRemark] = useState('');
    const [coupon, setCoupon] = useState<CouponItem | undefined>();
    const [totalPrice, setTotalPrice] = useState<number>(0);
    // 添加新状态：是否勾选确认信息
    const [isConfirmed, setIsConfirmed] = useState(() => {
        // 从本地存储读取保存的状态，默认为false
        // const savedState = Taro.getStorageSync('confirmOrder_isConfirmed');
        // return savedState !== undefined ? savedState : false;
        return false;
    });

    // 监听状态变化并保存到本地存储
    useEffect(() => {
        Taro.setStorageSync('confirmOrder_isConfirmed', isConfirmed);
    }, [isConfirmed]);
    // 创建一个引用，用于滚动到底部
    const bottomRef = useRef<HTMLDivElement>(null);

    // 创建订单
    const handleSubmit = async () => {
        const res = await myOrderApi.addOrder({
            shopCartIds: cartItems.map(item => item.id).join(','),
            appAddressId: selectedAddressId,
            couponId: coupon ? coupon.couponGetRecordId : 0,
            distributionModeId: activeDistributionMode,
            orderRemark: remark,
            packagePriceType: packgeType,
        });

        // 前端判断是不是0元
        if (totalPrice === 0) {
            Taro.redirectTo({
                url: `/subPages/MyOrder/MyOrder?orderState=`
            });
            return;
        }

        // 查看支付状态,  如果是0元已支付的话,就发起支付
        // const state = await myOrderApi.queryOrderState(res.msg);

        // // 如果是0元已支付的话, 就直接跳转到订单列表页
        // if (state.msg === "SUCCESS") {
        //     Taro.redirectTo({
        //         url: `/subPages/MyOrder/MyOrder?orderState=`
        //     });
        //     return;
        // }

        if (res.code === 200) {
            const res2 = await myOrderApi.pay(res.msg);
            // 发起支付
            Taro.requestPayment(
                {
                    ...res2.data,
                    complete: (res: TaroGeneral.CallbackResult) => {
                        Taro.redirectTo({
                            url: `/subPages/MyOrder/MyOrder?orderState=`
                        });
                    },
                    fail: (res: TaroGeneral.CallbackResult) => {
                        Taro.redirectTo({
                            url: `/subPages/MyOrder/MyOrder?orderState=`
                        });
                    },
                    success: (res: TaroGeneral.CallbackResult) => {
                        Taro.redirectTo({
                            url: `/subPages/MyOrder/MyOrder?orderState=`
                        });
                    }
                }
            );
        }
    };

    // 处理支付按钮点击
    const handlePaymentClick = () => {
        if (!isConfirmed) {
            // 如果没有勾选，滚动到底部
            const query = Taro.createSelectorQuery();
            query
                .select('.' + styles.confirmationContainer)
                .boundingClientRect()
                .selectViewport()
                .scrollOffset()
                .exec((res) => {
                    if (res[0] && res[1]) {
                        const offsetTop = res[0].top + res[1].scrollTop - 94;
                        Taro.pageScrollTo({
                            scrollTop: offsetTop,
                            duration: 300,
                        });
                    }
                });
            return;
        }

        // 确认支付
        handleSubmit();
    };

    // 判断是否有可用优惠券
    const hasAvailableCoupon = myCouponsStore.list.some(coupon => coupon.state === '未使用' && coupon.usePrice <= totalPrice);

    return (
        <View className={styles.confirmOrder}>
            <CustomHeader
                showBack={true}
                title="确认订单"
            />

            {/* 收货地址 */}
            <Cell
                className={styles.addressCell}
            >
                <View
                    className={styles.addressInfo}
                    onClick={() => {
                        addressManageStore.setSelectMode(true);
                        console.log("/subPages/AddressManage/AddressManage");
                        Taro.navigateTo({
                            url: '/subPages/AddressManage/AddressManage'
                        });
                    }}
                >
                    <Location className={styles.addressIcon} />
                    {
                        address.filter(item => item.appAddressId === selectedAddressId).map(item => {
                            return (
                                <View className={styles.addressContent}>
                                    <View className={styles.addressTop}>
                                        <Text className={styles.name}>{item.userName}</Text>
                                        <Text className={styles.phone}>{item.phone}</Text>
                                    </View>
                                    <Text className={styles.address}>{item.province}{item.city}{item.county}{item.detail}</Text>
                                </View>
                            )
                        })
                    }
                    <ArrowRight className={styles.arrowIcon} />
                </View>
            </Cell>

            {/* 商品列表 */}
            {/* <VirtualList
                className={styles.goodsList}
                itemHeight={120}
                containerHeight={sysInfo.windowHeight - navBarHeight - statusBarHeight - 300}
                list={cartItems}
                itemRender={(item, i) => (
                    <View key={i} className={styles.goodsItem}>
                        <Image src={item.image} className={styles.goodsImage} />
                        <View className={styles.goodsInfo}>
                            <Text className={styles.goodsName}>{item.name}</Text>
                            <View className={styles.goodsPrice}>
                                <Price price={item.price} size="normal" />
                                <Text className={styles.quantity}>x{item.quantity}</Text>
                            </View>
                        </View>
                    </View>
                )}
            /> */}

            <View className={styles.goodsList} >
                {
                    cartItems.map((cartItem, i) => {
                        return (
                            <View key={i} className={styles.goodsItem}>

                                <Image
                                    className={styles.goodsImage}
                                    src={utils.ossSuffix(cartItem.productDesign.thumbs[0], utils.rpx2px(260))}
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        if (cartItem.productDesign.thumbs.length > 1) {
                                            Taro.previewImage({
                                                urls: [
                                                    utils.ossSuffix(cartItem.productDesign.thumbs[0], 1024),
                                                    utils.ossSuffix(cartItem.productDesign.thumbs[1], 1024)
                                                ]
                                            });
                                        }
                                    }}
                                />
                                {
                                    cartItem.productDesign.thumbs[1] &&
                                    <Image
                                        className={styles.perImg}
                                        src={utils.ossSuffix(cartItem.productDesign.thumbs[1], utils.rpx2px(80))}
                                    />
                                }

                                {/* <Image
                                    src={utils.ossSuffix(cartItem.productShowImageUrl, 200)}
                                    className={styles.goodsImage}
                                /> */}
                                <View className={styles.goodsInfo}>
                                    <Text className={styles.goodsName}>{cartItem.designName}</Text>
                                    <Text className={styles.goodsCode}>编码: {cartItem.utStyleNum}</Text>
                                    {
                                        /^[\u4e00-\u9fa5]+$/.test(cartItem.color) &&
                                        <Text className={styles.goodsColor}>颜色: {cartItem.color}</Text>
                                    }
                                    <Text className={styles.goodsSize}>尺码: {cartItem.size}</Text>
                                    <View className={styles.goodsPrice}>
                                        <Price
                                            price={cartItem.pagePrice}
                                            size="normal"
                                            digits={1}
                                        />
                                        <Text className={styles.quantity}>x{cartItem.productNumber}</Text>
                                    </View>
                                </View>
                            </View>
                        )
                    })
                }
            </View>

            {/* 配送方式, 全包邮就不展示 */}
            {
                !cartItems.every(item => item.ifPinkage === "是") &&
                <Cell
                    title="配送方式"
                    className={styles.packingCheckbox}
                    extra={
                        // <Text className={styles.distributionModeText}>
                        //     {distributionMode.filter(item => item.distributionModeId === activeDistributionMode)[0]?.companyName}
                        // </Text>
                        <>
                            {
                                distributionMode.map((item, index) => {
                                    return (
                                        <Checkbox
                                            style={{ marginInlineEnd: '8px' }}
                                            // activeIcon={<Checklist />}
                                            shape="button"
                                            label={item.companyName}
                                            checked={item.distributionModeId === activeDistributionMode}
                                            onChange={(value: boolean) => {
                                                confirmOrderStore.setDistributionMode(item.distributionModeId);
                                            }}
                                        />
                                    );
                                })
                            }
                        </>
                    }
                // onClick={() => {
                //     Taro.showActionSheet({
                //         itemList: distributionMode.map(item => item.companyName),
                //         success: (res) => {
                //             confirmOrderStore.setDistributionMode(distributionMode[res.tapIndex].distributionModeId);
                //         },
                //         fail: (res) => { }
                //     });
                // }}
                />
            }

            {/* 包装方式 */}
            <Cell
                title={
                    <View
                        onClick={async () => {

                            // Taro.previewImage({
                            //     urls: packgeImas.map(item => utils.ossSuffix(item.url, 1024)),
                            // });
                        }}
                        className={styles.title} >
                        包装方式
                    </View>
                }
                className={styles.packingCheckbox}
                extra={
                    <>
                        {/* 普通包装 */}
                        <Checkbox
                            style={{ marginInlineEnd: '8px' }}
                            // activeIcon={<Checklist />}
                            shape="button"
                            label={`普通包装 ${commonPackage}元`}
                            checked={packgeType === 0}
                            onChange={(value: boolean) => {
                                confirmOrderStore.setPackgeType(0);
                            }}
                        />
                        {/* 礼盒包装 */}
                        <Checkbox
                            style={{ marginInlineEnd: '8px' }}
                            // activeIcon={<Checklist />}
                            shape="button"
                            label={`礼盒包装 ${advencedPackage}元/件`}
                            checked={packgeType === 1}
                            onChange={(value: boolean) => {
                                confirmOrderStore.setPackgeType(1);
                            }}
                        />
                    </>
                }
            />

            {
                <Image
                    src={packgeType === 0 ? packageImages.common : packageImages.advanced}
                    mode='widthFix'
                    // style={{ width: '240rpx', height: '240rpx', marginBottom: '10rpx' }}
                    style={{
                        width: "96vw",
                        margin: "2vw",
                        borderRadius: "40rpx",
                    }}
                    onClick={() => {
                        Taro.previewImage({
                            urls: [packgeType === 0 ? packageImages.common : packageImages.advanced],
                        });
                    }}
                />
            }

            {/* 优惠券 */}
            <Cell
                className={styles.couponCell}
                title="优惠券"
                extra={
                    <>
                        {coupon ?
                            <>
                                <Text className={styles.couponText}>
                                    {coupon.couponName}
                                </Text>
                                <Button
                                    type='primary'
                                    size='small'
                                    style={{ marginLeft: "20rpx" }}
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        confirmOrderStore.setCoupon(undefined);
                                    }}
                                >取消</Button>
                            </>
                            :
                            hasAvailableCoupon ? "有可用优惠券" : "没有可用优惠券"
                        }
                        <ArrowRight className={styles.arrowIcon} />
                    </>
                }
                onClick={() => {
                    if (!confirmOrderStore.coupon) {
                        myCouponsStore.setOrderPrice(totalPrice);
                        Taro.navigateTo({
                            url: '/subPages/MyCoupons/MyCoupons?selectMode=true'
                        })
                    }
                }}
            />

            {/* 在页面底部添加提示信息和复选框 */}
            <View ref={bottomRef} className={styles.confirmationContainer}>
                <View className={styles.confirmationWrapper}>
                    <Checkbox
                        checked={isConfirmed}
                        onChange={(value: boolean) => {
                            setIsConfirmed(value);
                        }}
                    />
                    <Text className={styles.confirmationText}>
                        我已仔细核对订单信息（印花图稿、颜色、尺码、数量及收货地址），确认无误并知悉付款后无法取消订单啦～!
                        <br />
                        本人确认上传图片拥有合法版权或授权，如因图片版权问题产生纠纷，责任由本人承担哦～
                    </Text>
                </View>
            </View>

            {/* 结算栏 */}
            <CustomTabBar>
                <View className={styles.footer}>
                    <View className={styles.totalPrice}>
                        <Text>合计: </Text>
                        <Price
                            price={totalPrice}
                            size="large"
                            digits={1}
                        />
                    </View>
                    <Button
                        type="warning"
                        className={clsx(styles.submitButton, !isConfirmed && styles.gray)}
                        onClick={handlePaymentClick}
                    >
                        支付
                    </Button>
                </View>
            </CustomTabBar>
        </View>
    );
});

export default ConfirmOrder;